// import { v4 as uuidv4 } from 'uuid'
import GeneralDataTable from './generalDataTable.js'
export default class DataSet {
	constructor(dataSet){
		this.id = this.guid()
		this.dataTables = []
		this.DataSet(dataSet)
	}
	DataSet(dataSet = null) {
		if(dataSet){
			if( typeof dataSet === 'string'){
				dataSet = JSON.parse(dataSet);
			}
			this.id = dataSet.id;
			for (let i in dataSet.dataTables) {
				let dataTable = this.createSimpleDateTable(dataSet.dataTables[i].schema.name);
				dataTable.id = dataSet.dataTables[i].schema.id;
				dataTable.name = dataSet.dataTables[i].schema.name;
				dataTable.label = dataSet.dataTables[i].schema.label;
				dataTable.type = dataSet.dataTables[i].schema.type;
				for (let j in dataSet.dataTables[i].schema.columns) {
					let col = dataSet.dataTables[i].schema.columns[j];
					if ("String" == col.type) {
						dataTable.createStringDataColumn(col.name, col.label, col.stringSize);
					}
					if ("Long" == col.type) {
						dataTable.createLongDataColumn(col.name, col.label);
					}
					if ("Boolean" == col.type) {
						dataTable.createBooleanDataColumn(col.name, col.label);
					}
					if ("Decimal" == col.type) {
						dataTable.createDecimalDataColumn(col.name, col.label);
					}
					if ("Date" == col.type) {
						dataTable.createDateDataColumn(col.name, col.label);
					}
					if ("Time" == col.type) {
						dataTable.createTimeDataColumn(col.name, col.label);
					}
					if ("DataTime" == col.type) {
						dataTable.createDateTimeDataColumn(col.name, col.label);
					}
					if ("Enum" == col.type) {
						let enumItems = {};
						for (let h in col.enumItems) {
							enumItems[col.enumItems[h].name] = col.enumItems[h].value;
						}
						dataTable.createEnumDataColumn(col.name, col.label, enumItems);
					}
				}
				for (let g in dataSet.dataTables[i].data) {
					let row = dataSet.dataTables[i].data[g];
					let datarow = dataTable.createDataRow();
					for (let key in row)
						datarow.setCellValue(key, row[key]);
				}
			}
		}
		
	}
	createSimpleDateTable(dataTableName) {
		const optional = this.dataTables.filter(item => {
			return item.name === dataTableName
		})
		if (Object.keys(optional).length) {
			alert("数据表" + dataTableName + "已存在，不允许重复添加")
		} else {
			let dataTable = new GeneralDataTable(dataTableName);
			this.dataTables.push(dataTable)
			return dataTable
		}
	}
	getDataTable(index){
		if(index>=this.dataTables.length){
			alert("不存在下标为【"+index+"】的DataTable")
		}
		return this.dataTables[index]
	}

	guid() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}
}
